const express = require('express');
const cors = require('cors');
const multer  = require('multer');
const fs = require('fs');

const archiver = require('archiver');
const app = express();
// 使用cors中间件
app.use(cors());

var count = 0;
var total = 10;
var folder = '';
var setData = {top:20,left:20,bottom:20,right:20};
var zipstr = 'zip is empty';

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})
const upload = multer({ storage: storage });
 
// 处理上传的文件
app.post('/upload', upload.single('myFile'), (req, res) => {
    const file = req.file;
    if (!file) {
        return res.status(400).send('No file uploaded.');
    }
    console.log(file, '-->');
    zipstr = 'zip is empty';
    // 文件信息在req.file
    // 同步创建文件夹
    try {
        var arr = file.originalname.split(".");
        folder = arr[0];
        fs.mkdirSync(folder, { recursive: true });
        console.log('文件夹创建成功');
    } catch (err) {
        console.error(err);
    }
 
    // 读取文件内容
    fs.readFile(file.path, 'utf-8', (err, data) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error reading file.');
        } else {
            // 成功读取文件内容，data变量包含文件内容
            // console.log(data);
            console.log("进来了！");
            // res.send('File uploaded and content read successfully.');

            var values = [];
            var content = data;
            var arr1 = content.split("INSERT INTO `hzyy_instruction_data` (");
            var str;
            arr1.shift();
            for(var i=0; i<arr1.length; i++){
                str = arr1[i];
                if(!str){
                    continue;
                }
                var attrs = str.substring(0, str.indexOf(") VALUES ("));
                var attrArr = attrs.split(", ");
                
                var value = str.substring(str.indexOf("VALUES (")+8, str.length -3);
                var valueArr = value.split(", '");
                values[i] = [];
                for(var j=0; j<attrArr.length; j++){
                    if(valueArr[j] && j == valueArr.length-1){
                        valueArr[j] = valueArr[j].replace("'","");
                        let regex = /<table/g; // g标志表示全局匹配
                        if(valueArr[j].indexOf("<table") != -1){
                                valueArr[j] = valueArr[j].replace(regex, '<table border="1" ');
                            }
                        values[i].push({key:attrArr[j], value:valueArr[j]});
                    }
                    
                }
                // sql.value = values;
                // curWord.value = sql.value[page];
            }
            var index = 0;
            console.log("<-----length=",values.length,"------>");
            total = values.length;
            var tid = setInterval(() => {
                console.log("----->",(index));

                if(index >= values.length){
                    clearInterval(tid);
                    setTimeout(() => {
                        exeZIP();
                    }, 1000);
                    return;
                }
                // 使用示例
                const htmlContent = '<html><body>'+values[index][0].value+'</body></html>';
                // var htmlContent = '<html><body><div style="display:flex;flex-direction: row;">';
                // htmlContent += '<div>'+values[index][0].value+'</div>';
                // htmlContent += '<div>'+values[index][0].value+'</div>';
                // htmlContent += '<div>'+values[index][0].value+'</div>';
                // htmlContent += '<div>'+values[index][0].value+'</div>';
                // htmlContent += '</div></body></html>';

                const printFun = (async (ai, aj) => {
                    // 生成PDF
                    const pdfBuffer = await generatePDF(htmlContent);
                    // 将PDF保存到文件（可选）
                    if(pdfBuffer){
                        fs.writeFileSync( "./"+folder+"/" + (ai+'_') + 'output.pdf', pdfBuffer);
                    }
                });
                printFun(index, 0);
                index ++;
                count = index;

            }, 100);
            
        }
    });
    // res.send('File uploaded successfully.');
});
app.get('/process', function (req, res) {
    // console.log("进度查询！");
    res.send(count + '/' + total + '/' + zipstr);
 })
app.get('/set', function (req, res) {
    console.log("pdf设置！",req.query);
    setData = req.query;
    res.send('设置成功');
})

app.get('/download', (req, res) => {
    if(count < total){
        res.send('尚未解析完成！');
        return;
    }
    const filePath = './'+folder+'/output.zip'; // 替换为实际文件路径

    try{
        const fileStream = fs.createReadStream(filePath);
        fileStream.pipe(res);
    }catch(e){
        console.log(e);
    }

    res.setHeader('Content-disposition', 'attachment; filename=file.zip');
    res.setHeader('Content-type', 'application/octet-stream');
});
 
const PORT = 3002;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

const readFiles = () => {
    return new Promise( function(resolve, reject){
        // 做一些处理，比如保存文件信息到数据库等
        var nameArr = [];
        fs.readdir(folder, (err, files) => {
          if (err) {
            console.error(err);
            resolve(nameArr);
          }
          
          files.forEach(file => {
            console.log(file);
            if(file.indexOf(".zip") == -1){
                nameArr.push({ path: './'+folder+'/'+file, name: file });
            }
          });
        //   console.log("sdlkkslds,",nameArr);
          resolve(nameArr);
        })
      });
  }
// const readFiles = new Promise( function(resolve, reject){
//     // 做一些处理，比如保存文件信息到数据库等
//     var nameArr = [];
//     fs.readdir('pdf', (err, files) => {
//       if (err) {
//         console.error(err);
//         resolve(nameArr);
//       }
      
//       files.forEach(file => {
//         console.log(file);
//         if(file.indexOf(".zip") == -1){
//             nameArr.push({ path: './pdf/'+file, name: file });
//         }
//       });
//     //   console.log("sdlkkslds,",nameArr);
//       resolve(nameArr);
//     })
//   });
function exeZIP(){
    // // 使用示例
    // const filesToZip = [
    //     { path: 'path/to/your/file1.txt', name: 'file1.txt' },
    //     { path: 'path/to/your/file2.jpg', name: 'file2.jpg' }
    // ];
    // const zipPath = 'path/to/your/output.zip';
    
    // createZip(filesToZip, zipPath);
    console.log("-->执行zip操作");
    readFiles().then( data => {
        var nameArr = data;
        if(nameArr.length >= total){
            const zipPath = './'+folder+'/output.zip';
            console.log("-->生成zip");
            createZip(nameArr, zipPath);
        }
        else{
            setTimeout(() => {
                exeZIP();
            }, 1000);
        }
      });
}
const puppeteer = require('puppeteer-core');
// var browser;
// var page;

async function generatePDF(html) {
    try{
    // 启动浏览器
    // if(!browser){
        const browser = await puppeteer.launch({
            // executablePath: './chrome-win/chrome.exe'
            executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe'
          });
    // }
    
    // 创建一个新页面
    // if(!page){
        const page = await browser.newPage();
        await page.setDefaultNavigationTimeout(0);
    // }
    
    // 设置HTML内容
    await page.setContent(html, {
        waitUntil: 'networkidle0'
    });
    // 导出PDF
    const pdf = await page.pdf({
        format: 'A3',
        printBackground: true,
        margin: {
            top: setData.top+'px',
            right: setData.right+'px',
            bottom: setData.bottom+'px',
            left: setData.left+'px'
        },
        landscape:true,
        preferCSSPageSize:true,
        width:"4in"
    });
    // // 关闭浏览器
    await browser.close();
    // PDF数据
    return pdf;

    }catch(e){
        console.error(e);
        return null;
    }
    
}
/**
 * 打包zip
 */
function createZip(files, outputPath) {
    console.log("创建zip中");
    let output = fs.createWriteStream(outputPath);
    let archive = archiver('zip', {
      zlib: { level: 9 } // Sets the compression level.
    });
   
    // Event listener for all archive data to be written
    output.on('close', function() {
      console.log(archive.pointer() + ' total bytes');
      console.log('Zip file has been created');
      zipstr = "zip is ok"

    });
   
    // This event is fired when the file data is actually written on disk
    archive.on('warning', function(err) {
      if (err.code === 'ENOENT') {
        // log warning
        console.warn(err);
      } else {
        // throw error
        throw err;
      }
    });
   
    // This event is fired when there is an error while creating the zip file
    archive.on('error', function(err) {
      throw err;
    });
   
    // Pipe archive data to the file
    archive.pipe(output);
   
    // Append files from the `files` array to the archive
    files.forEach(function(file) {
      archive.append(fs.createReadStream(file.path), { name: file.name });
    });
   
    // Finalize the archive (ie we are done appending files but zlib needs to finish for the file to be written)
    // 'close', will be fired after stream has finished
    archive.finalize();
  }
 



// const puppeteer = require('puppeteer-core');

// (async () => {
//   const browser = await puppeteer.launch({
//     executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe'
//   });
//   const page = await browser.newPage();
//   await page.goto('https://y.qq.com');
//   await page.screenshot({path:'yqq.png'});
//   browser.close();
// })()


// const fs = require("fs");
// // const {compile} = require("ejs"); // ^3.1.10
// const express = require("express"); // ^4.19.2
// const puppeteer = require("puppeteer-core"); // ^22.7.1

// const app = express();

// async function _generateHtml(data, templatePath) {
//   const template = fs.readFileSync(templatePath, "utf8");
//   const html = compile(template);
//   return html(data);
// }

// app.get("/", async (req, res) => {
//     console.log('进来了');
//   //const browser = await puppeteer.launch({headless: true});
//   const browser = await puppeteer.launch({
//     executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe'
//   });

//   const page = await browser.newPage();
// //   const html = await _generateHtml({}, "offer-template.ejs");
//   // 使用示例
//     const htmlContent = '<html><head><title>PDF Example</title></head><body><h1>Hello, world!</h1></body></html>';
//   await page.setContent(htmlContent);

//   const pdfBuffer = await page.pdf({
//     printBackground: true,
//   });
//   res.set("Content-Type", "application/pdf");
//   res.send(pdfBuffer);
// });

// app.listen(3002, () => {
//     console.log('Server listening on port 3002');
//   })



// const puppeteer = require('puppeteer');
 
// async function generatePDF(html) {
//     // 启动浏览器
//     const browser = await puppeteer.launch();
//     // 创建一个新页面
//     const page = await browser.newPage();
//     // 设置HTML内容
//     await page.setContent(html, {
//         waitUntil: 'networkidle0'
//     });
//     // 导出PDF
//     const pdf = await page.pdf({
//         format: 'A4',
//         printBackground: true
//     });
    
//     // 关闭浏览器
//     await browser.close();
    
//     // PDF数据
//     return pdf;
// }
 
// // 使用示例
// const htmlContent = `
//     <html>
//         <head><title>PDF Example</title></head>
//         <body><h1>Hello, world!</h1></body>
//     </html>
// `;
 
// (async () => {
//     // 生成PDF
//     const pdfBuffer = await generatePDF(htmlContent);
    
//     // 将PDF保存到文件（可选）
//     const fs = require('fs');
//     fs.writeFileSync('output.pdf', pdfBuffer);
// })();